<script>
import {blurElement, formatDate, gradeElement} from "../../../util/js/utils";
import AddUser from "./dialog/AddUser.vue";
import {deleteUser, resetPassword, searchUser, updateStatus} from "./UserListJs";
import {dictionaryRequest} from "../../../util/js/globalRequestJs";
import EditUser from "./dialog/EditUser.vue";

export default {
  components: {
    'add-dialog': AddUser,
    'edit-dialog': EditUser,
  },
  name: "UserList",
  data() {
    return {
      isAddVisible: false, // 控制新增弹窗的显隐
      editData: {},
      isEditVisible: false, // 控制编辑弹框
      tableData: [],  // 表格数据

      currentPage: 1,
      pageSize: 5,
      totalNumber: 0,

      multipleSelection: [], //选中行数据
      userType: '-1',
      statusType: '1',
      searchContext: '', // 搜索内容
      searchType: '', //内容类型
      types: [],
      statuses: []

    }
  },
  mounted() {
    this.search(); // 刷新数据
    this.downSelect(); // 获取下拉数据
  },
  methods: {
    formatDate, // 设置时间格式
    // 处理选中行的数据保存
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.search();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.search();
    },

    // 获取下拉栏数据
    downSelect() {
      dictionaryRequest('user', 'type').then(res => {
        this.types = res.data;
      }).catch(error => {
        console.log(error);
      });
      dictionaryRequest('user', 'status').then(res => {
        this.statuses = res.data;
      }).catch(error => {
        console.log(error);
      });
    },

    // 搜索
    search() {
      // 获取数据
      const _this = this;
      const searchData = {
        "searchType": _this.searchType,
        "searchContext": _this.searchContext,
        "userType": _this.userType,
        "statusType": _this.statusType,
        "currentPage": _this.currentPage,
        "pageSize": _this.pageSize
      }
      // 发送请求
      searchUser(searchData).then(res => {
        if (res.code === '200') {
          _this.tableData = res.data.data;
          _this.totalNumber = res.data.totalNumber;
          _this.multipleSelection = [] // 清空选择
        } else {
          _this.$message.error(res.msg);
        }
      }).catch(err => {
        console.log("系统出错了", err);
      })
    },

    // 关闭弹窗
    closeDialog() {
      if (this.isEditVisible) {
        this.isEditVisible = false;
      }
      if (this.isAddVisible) {
        this.isAddVisible = false;
      }
      // 设置层次等级并设置模糊
      gradeElement('ul-dialog-container', 1)
      blurElement('ul-context-container', 0);
      // 刷新数据
      this.search();
    },

    // 新增用户
    addUser() {
      // 打开弹窗
      this.isAddVisible = true;
      // 设置层次等级并设置模糊
      gradeElement('ul-dialog-container', 3)
      blurElement('ul-context-container', 1.5);
    },

    // 删除用户
    deleteUser(row) {
      const _this = this;
      let ids = []
      // 获取选中行的ID信息
      if (row !== undefined) {
        ids.push(row.uuuid);
      } else {
        if (_this.multipleSelection.length === 0) {
          _this.$message.warning("您未选中数据！")
          return null;
        }
        ids = _this.multipleSelection.map(row => row.uuuid);
      }
      _this.$confirm("请再次确认是否删除用户信息", "提示", {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        deleteUser(JSON.stringify(ids)).then(res => {
          if (res.code === '200') {
            _this.$message.info('删除成功')
            // 刷新用户信息
            _this.search();
          } else {
            _this.$message.error(res.msg);
          }
        }).catch(error => {
          console.log('系统出错了！', error);
        })
      }).catch(() => {
        _this.$message.info('已取消删除')
      })
    },

    // 编辑用户
    editUser(row) {
      const _this = this;
      _this.editData = row;
      _this.isEditVisible = true;
      // 设置层次等级并设置模糊
      gradeElement('ul-dialog-container', 3)
      blurElement('ul-context-container', 1.5);
    },

    // 修改用户状态
    toggleStatus(row, index) {
      const _this = this;
      // 获取状态信息确定功能，禁用状态为启用功能，非禁用则为禁用功能
      if (row.status === '禁用') {
        // 启用
        updateStatus(row.uuuid, '1').then(res => {
          if (res.code === '200') {
            _this.$message.success("数据" + (index + 1) + "启用成功!")
            // 获取数据
            _this.search();
          } else {
            _this.$message.error(res.msg);
          }
        }).catch(error => {
          console.log("系统出错了!", error)
        })
      } else {
        // 禁用
        updateStatus(row.uuuid, '0').then(res => {
          if (res.code === '200') {
            _this.$message.success("数据" + (index + 1) + "禁用成功!")
            // 获取数据
            _this.search();
          } else {
            _this.$message.error(res.msg);
          }
        }).catch(error => {
          console.log("系统出错了!", error)
        })
      }
    },

    // 清除搜索
    cleanSearch() {
      this.userType = '-1';
      this.statusType = '1';
      this.searchContext = ''; // 搜索内容
      this.searchType = ''; //内容类型
      this.search();
    },

    // 重置密码
    resetPwd() {
      const _this = this;
      // 检查是否选中用户并设置用户ID
      if (_this.multipleSelection.length === 0) {
        _this.$message.warning("您未选中数据！")
        return null;
      }
      const ids = _this.multipleSelection.map(row => row.uuuid);

      // 重置
      resetPassword(ids).then(res => {
        if (res.code === '200') {
          _this.$message.success("重置成功!");
          _this.search()
        } else {
          _this.$message.error("重置失败，请重试!");
        }
      }).catch(error => {
        console.log("系统出错了!", error);
      })
    }
  }
}
</script>

<template>
  <!--  主容器  -->
  <div id="ul-main-container" class="ul-main-container">
    <div id="ul-context-container" class="ul-second-container">
      <div id="ul-operate-container" class="ul-operate-container">
        <div class="ul-button-container">
          <el-button v-authority="'老板'" type="primary" icon="el-icon-delete" size="small"
                     @click="deleteUser(undefined)"></el-button>
          <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="addUser"></el-button>
          <el-button type="primary" size="small" @click="resetPwd">重置密码</el-button>
        </div>

      </div>
      <div id="ul-search-container" class="ul-search-container">
        <div id="ul-search-one" class="ul-search-one">
          <el-select v-model="userType" style="width: 130px"
                     slot="prepend" placeholder="请选择" size="mini">
            <el-option label='请选择用户类型' value="-1"></el-option>
            <el-option
              v-for="option in types"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            ></el-option>
          </el-select>
          <el-select v-model="statusType" style="width: 130px"
                     slot="prepend" placeholder="请选择" size="mini">
            <el-option
              v-for="option in statuses"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            ></el-option>
          </el-select>
        </div>
        <div id="ul-search-two" class="ul-search-two">
          <el-input placeholder="请输入内容" v-model="searchContext" class="input-with-select" style="width: 400px">
            <el-select v-model="searchType" slot="prepend" placeholder="请选择">
              <el-option label="真实姓名" value="1"></el-option>
              <el-option label="手机号" value="2"></el-option>
              <el-option label="身份证号" value="3"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
          <el-button slot="append" @click="cleanSearch">清空<i class="el-icon-s-help"></i></el-button>
        </div>
      </div>
      <div id="ul-table-container">
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          border
          height="100%"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <!--===================序号=====================-->
          <el-table-column
            type="index"
            width="30"
            align="center">
          </el-table-column>
          <!--===================选中=====================-->
          <el-table-column
            type="selection"
            align="center"
            width="55">
          </el-table-column>
          <!--===================uuid(隐藏)=====================-->
          <el-table-column
            v-if=false
            prop="uuuid"
            align="center">
          </el-table-column>
          <!--===================用户名=====================-->
          <el-table-column
            prop="name"
            label="用户名"
            align="center"
            width="100">
          </el-table-column>
          <!--===================真实姓名=====================-->
          <el-table-column
            prop="realName"
            label="真实姓名"
            align="center"
            width="100">
          </el-table-column>
          <!--===================性别=====================-->
          <el-table-column
            prop="sex"
            label="性别"
            align="center"
            width="50">
          </el-table-column>
          <!--===================年龄=====================-->
          <el-table-column
            prop=age
            label="年龄"
            align="center"
            width="60">
            <template slot-scope="scope">
              {{ scope.row.age }}&nbsp;岁
            </template>
          </el-table-column>
          <!--===================联系电话=====================-->
          <el-table-column
            prop="phone"
            label="联系电话"
            align="center"
            width="120">
          </el-table-column>
          <!--===================身份证号=====================-->
          <el-table-column
            prop="identity"
            label="身份证号"
            align="center"
            width="180">
          </el-table-column>
          <!--===================用户类型=====================-->
          <el-table-column
            prop="type"
            label="用户类型"
            align="center"
            width="150">
          </el-table-column>
          <!--===================状态=====================-->
          <el-table-column
            prop="status"
            label="状态"
            align="center"
            width="60">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.status === '禁用' ? 'red' : 'green' }">{{ scope.row.status }}</span>
            </template>
          </el-table-column>
          <!--===================最近登录=====================-->
          <el-table-column
            prop="lastLogTime"
            label="最近登录"
            align="center"
            width="100">
            <!-- 使用 formatter 自定义时间格式 -->
            <template slot-scope="scope">
              <span :style="{ color: scope.row.lastLogTime === null ? 'red': ''}">
                {{ scope.row.lastLogTime === null ? '从未登录过' : formatDate(scope.row.lastLogTime) }}
              </span>

            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作">
            <template slot-scope="scope">
              <el-button v-authority="'老板'" @click="deleteUser(scope.row)" type="text" size="small">删除
              </el-button>
              <el-button @click="editUser(scope.row)" type="text" size="small">编辑</el-button>
              <el-button @click="toggleStatus(scope.row,scope.$index)" type="text" size="small"
                         :style="{ color: scope.row.status === '禁用' ? 'green' : 'red' }">
                {{ scope.row.status === '禁用' ? '启用' : '禁用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="block">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalNumber"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange">
        </el-pagination>
      </div>
    </div>
    <div id="ul-dialog-container" class="ul-dialog-container">
      <div v-if="isEditVisible" class="ul-dialog">
        <edit-dialog :editData="editData" @closeEdit="closeDialog"/>
      </div>
      <div v-if="isAddVisible" class="ul-dialog">
        <add-dialog @closeAdd="closeDialog"/>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import "UserListCss.css";
</style>
